#include "widget.h"
#include "ui_widget.h"
#include <QDateTime>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    cam(0),
    frame(0),
    hit(0)
{
    ui->setupUi(this);

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Widget::update);
    timer->start(40);

    std::string model = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml";
    face = new Face(model);
    face->moveToThread(&facethread);

    qRegisterMetaType<cv::Mat>("cv::Mat");
    qRegisterMetaType<cv::Rect>("cv::Rect");
    qRegisterMetaType<Employee>("Employee");

    connect(this, &Widget::doDetect, face, &Face::detect);
    connect(face, &Face::detected, this, &Widget::updateFace);
    connect(this, &Widget::doRecognize, face, &Face::recognize);
    connect(face, &Face::recognized, this, &Widget::updateInfo);
    connect(&facethread, &QThread::finished, face, &Face::deleteLater);

    facethread.start();//启动人脸识别线程
    db = new Database("attend.db");
}

void Widget::updateFace(cv::Rect face)
{
    range = face;
    if (face != cv::Rect(0,0,0,0))
    {
        hit++;
    }
    else {
        hit = 0;
    }
}

void Widget::updateInfo(Employee user)
{
    time_t now = QDateTime::currentDateTime().toTime_t();
    if (db->punch(user.id, now))
    {
        return;
    }

    std::string name = "";
    if (db->getname(user.id, name))
    {
        return;
    }

    ui->label_id->setText(user.id.c_str());
    ui->label_name->setText(name.c_str());
    ui->label_time->setText(QDateTime::fromTime_t(now).toString("ap h:m:s"));
}

void Widget::update()
{
    cv::Mat image;

    cam >> image;
    frame++;
    if ((frame%5) == 0)
    {
         //t.start();
         emit doDetect(image);
         //std::cout << "detect: " << t.elapsed() << std::endl;
    }
    if (5 == hit)
    {
        cv::Mat faceimg(image, range);
        //t.start();
        emit doRecognize(faceimg);
        //std::cout << "recognize: " << t.elapsed() << std::endl;
    }
    cv::rectangle(image, range, CV_RGB(255, 0, 0));
    cv::cvtColor(image, image, CV_BGR2RGB);
    QImage qimage(image.data, image.cols, image.rows,
                  image.step, QImage::Format_RGB888);
    ui->label->setPixmap(QPixmap::fromImage(qimage));
}

Widget::~Widget()
{
    delete ui;
    facethread.quit();
    facethread.wait();
}
